using System;
using System.Collections.Generic;
using L2NH.Core;
using L2NH.Core.Domain;
using NHibernate;

namespace L2NH.Infrastructure.DataAccess
{
   public class NHRepository : IRepository
   {
      public NHRepository()
      {
         _session = UnitOfWork.CurrentSession;
      }

      private readonly ISession _session;

      public T Get<T>(int id) where T : Entity
      {
         return _session.Get<T>(id);
      }

      public T Load<T>(int id) where T : Entity
      {
         return _session.Load<T>(id);
      }

      public IEnumerable<T> FindAll<T>() where T : Entity
      {
         return _session.CreateCriteria<T>().List<T>();
      }

      public void Add<T>(T entity) where T : Entity
      {
         _session.Save(entity);
      }

      public void Remove<T>(T entity) where T : Entity
      {
         _session.Delete(entity);
      }

      public void SubmitChanges()
      {
         try
         {
            _session.Transaction.Commit();
            _session.BeginTransaction();
         }
         catch
         {
            _session.Transaction.Rollback();
            throw;
         }
      }
   }
}